﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Threading;
using System.Drawing;
using HtmlAgilityPack;
using System.Web;
namespace GetContent
{
    class DataFilterRaoVat : DataFilter
    {
        private const string rootUrl = @"http://raovat.com/";
        
        public DataFilterRaoVat()
        {
            this.Cc.Add(new Uri(rootUrl), new Cookie("tinhthanhpho", "61"));
        }
        public List<string> getLinks(string link)
        {
           
            var listLink = new List<string>();
            var html = (string)this.GetData(link,null,null,false);
            var htmldoc = new HtmlAgilityPack.HtmlDocument();
            try {
                htmldoc.LoadHtml(html);
                var liNodes = htmldoc.DocumentNode.SelectNodes(@"//*[@class='tinrao_list']//li");
                foreach (var notes in liNodes)
                {
                    var linknotes = notes.SelectNodes("a[1]");
                    if (linknotes != null)
                    {
                        foreach (var linknote in linknotes)
                        {
                            listLink.Add(rootUrl + linknote.GetAttributeValue("href", ""));
                        }
                    }

                }
                return listLink;

            }
            catch (Exception ex)
            {
                return null;
            }
            
        }

        public baseItem getSingleLink(string link)
        {
            var content = "";
            string author = "", title = "", phone = "" ,date = "";
            var html = (string)this.GetData(link, null, null, false);
            var htmldoc = new HtmlAgilityPack.HtmlDocument();
            htmldoc.LoadHtml(html);

            
            var noidung = htmldoc.DocumentNode.SelectSingleNode(@"//*[@id='noidung_tin']");
            var titleNode = noidung.SelectSingleNode(@"//*[@class='tinrao_list_chitiet_title']");
            var authorNode = noidung.SelectSingleNode(@"//*[@class='tinrao_thongtindang']");
            var detailNode = noidung.SelectSingleNode(@"//*[@id='tinrao_chitiet_tinrao']");

            if (titleNode != null) title = titleNode.InnerText;
            if (authorNode != null) { 
                author = authorNode.InnerText;
                phone = this.GetPhone(author);
                date = this.GetDate(author);
            }
            if (detailNode != null) content = detailNode.InnerText;
            content  = HttpUtility.HtmlDecode(content);
            
            
            
            var item = new baseItem(link,title, content, phone);
            return item;
        }


        public List<baseItem> GetContent(List<string> listLink, ToolStripProgressBar progressBar, string filter = null)
        {
            //List<string> listLink = this.getLinks(link);
            var listItem = new List<baseItem>();
            if (listLink.Count < 0) return null;
            var count = 0;
            foreach (var l in listLink)
            {
                
                var item = this.getSingleLink(l);
                count++;
                progressBar.Value = count;
                if (item != null) {
               //Check Phone 
               var allPhone = File.ReadAllText(Application.StartupPath + "\\phoneList.txt");
               var isExists = allPhone.Contains(item.Phone);
               
               //Check Filter   
               var checkFilter = true;
               if (filter != "")
               {
                   var listFind = Regex.Split(filter, ";");
                   var listOfStr = new List<string>(listFind);
                   checkFilter =  this.CheckMatch(listOfStr, item.Content);
               }

               if (checkFilter && !isExists)
               {
                   var filePhone = "phoneList.txt";
                   this.Write2File(item.Phone, filePhone);

                   var time = DateTime.Now.ToString("yyyy-MM-dd HH-mm tt");
                   var fileResult = time + "-result.txt";
                   this.Write2File(item.Link + ";" + item.Phone + ";" + item.Title + ";" + item.Content, fileResult);
                   listItem.Add(item);
               }

               }
                
            }

            //check condition here 
            return listItem;
         }

        public void Write2File(string phone , string file)
        {
            var path = Application.StartupPath;

            using (var oFile = File.AppendText(path + "\\" + file))
            {
                var output = phone;
                oFile.WriteLine(output);
                oFile.Close();
            }
        }

        public void Begin()
        {
            //Working = true;

            Random rnd = new Random();
            int delay = rnd.Next(0, 20);
            Delay(delay);
            var cLink = PhoneList.linkIsExists(this._singleLink);
             
            var content = "";
            string author = "", title = "", phone = "", sdate = "";
            this.Status.Style.BackColor = Color.Yellow;
            this.Status.Value = "Getting HTML";
            Thread.Sleep(1000);
            var html = (string)this.GetData(this._singleLink, null, null, false);
            if (html == null)
            {
                this.Status.Value = "Cannot get HTML";
                this.Status.Style.BackColor = Color.Red;
                Thread.Sleep(1000);
                return;
            }

            this.Status.Value = "Parse HTML";
            Thread.Sleep(1000);

            var htmldoc = new HtmlAgilityPack.HtmlDocument();
            htmldoc.LoadHtml(html);


            var noidung = htmldoc.DocumentNode.SelectSingleNode(@"//*[@id='noidung_tin']");
            var titleNode = noidung.SelectSingleNode(@"//*[@class='tinrao_list_chitiet_title']");
            var authorNode = noidung.SelectSingleNode(@"//*[@class='tinrao_thongtindang']");
            var detailNode = noidung.SelectSingleNode(@"//*[@id='tinrao_chitiet_tinrao']");

            if (titleNode != null) title = titleNode.InnerText;
            if (authorNode != null)
            {
                author = authorNode.InnerText;
                phone = this.GetPhone(author);
                sdate = this.GetDate(author);
            }


            
            if (detailNode != null) content = detailNode.InnerText;
            content = HttpUtility.HtmlDecode(content);

            var item = new baseItem(this._singleLink, title, content, phone);
            //Check Link is exists
            

            if (item != null)
            {
                
                var phoneCondition = false;
                var phoneLimit = Configs.ReadValue("phoneLimit");
                var phoneCount = PhoneList.Count(item.Phone);
                if (phoneCount > int.Parse(phoneLimit)) {
                    phoneCondition = false;
                }
                else {
                    phoneCondition = true;
                    
                }
                

                //Check Date 
                var itemDate = convert2Date(sdate);
                var cDate = true;
                cDate = CheckDate(itemDate);

                //MessageBox.Show("Dobe");
                //Check Filter   
                var checkFilter = true;
                if (this._filter != "")
                {
                    var listFind = Regex.Split(this._filter, ",");
                    var listOfStr = new List<string>(listFind);
                    checkFilter = this.CheckMatch(listOfStr, item.Content);
                }

                if (checkFilter && phoneCondition && cDate)
                {
                    //var filePhone = "phoneList.txt";
                    //this.Write2File(item.Phone, filePhone);
                    var time = DateTime.Now.ToString("yyyy-MM-dd HH-mm tt");
                    var fileResult = time + "-result.txt";
                    this.Write2File("Link : "+item.Link + "\nPhone : " + item.Phone + "\nTitle : " + item.Title + "\nContent : " + item.Content, fileResult);
                    if (cLink < 1)
                    {
                    PhoneList.AddPhone(item.Link, item.Phone);
                    }
                    //listItem.Add(item);
                    this.Status.Value = "Completed!";
                    this.Status.Style.BackColor = Color.Green;
                    Thread.Sleep(1000);
                }
                else
                {
                    this.Status.Value = "Fail!Not Match Condition";
                    this.Status.Style.BackColor = Color.Red;
                    Thread.Sleep(1000);
                }

            }
            else
            {
                this.Status.Value = "Cannot Parse HTML";
                this.Status.Style.BackColor = Color.Red;
                Thread.Sleep(1000);
            }
           

        }


        public void Start(string singleLink , string filter)
        {
            try
            {
                this._singleLink = singleLink;
                this._filter = filter;
                //Begin();
                
                var mainThread = new Thread(Begin);
                mainThread.Start();
            }
            catch (Exception ex)
            {
                _lastError = ex.Message;
            }
        }

        public DateTime convert2Date(string date)
        {
            DateTime d;
            if (date.Length > 0)
            {
                d = System.DateTime.ParseExact(date, "dd-MM-yy", null);
                return d;
            }
            else
            {
                return DateTime.Now;
            }
        }
      




    }
}
